package com.mayundev.pa.service.impl;

import com.mayundev.pa.model.ChatRequestEntity;
import com.mayundev.pa.model.ChatResponseEntity;
import com.mayundev.pa.service.AIService;
import com.mayundev.pa.util.MessageBuilder;
import com.mayundev.pa.util.ResponseConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;

@Slf4j
@Service
@ConditionalOnProperty(name = "ai.provider", havingValue = "deepseek")
public class DeepSeekServiceImpl implements AIService {

    @Autowired
    @Qualifier("openAiChatModel")
    private org.springframework.ai.chat.model.ChatModel chatModel;

    @Override
    public ChatResponseEntity simpleChat(ChatRequestEntity request) {
        try {
            List<Message> messages = MessageBuilder.buildMessages(request);
            Prompt prompt = new Prompt(messages);
            log.debug("发送请求到DeepSeek API，prompt：{}", prompt);
            ChatResponse response = chatModel.call(prompt);
            log.debug("API调用成功，响应内容：{}", response.getResult());
            return ResponseConverter.processSimpleResponse(response);
        } catch (Exception e) {
            log.error("API调用失败，错误信息：{}", e.getMessage(), e);
            throw new RuntimeException("调用AI服务失败：" + e.getMessage(), e);
        }
    }

    @Override
    public Flux<ChatResponseEntity> chatStream(ChatRequestEntity request) {
        try {
            List<Message> messages = MessageBuilder.buildMessages(request);
            Prompt prompt = new Prompt(messages);
            log.debug("发送流式请求到DeepSeek API，prompt：{}", prompt);

            final boolean[] isThinking = {false};

            return chatModel.stream(prompt)
                    .map(response -> ResponseConverter.processStreamResponse(response, isThinking))
                    .doOnNext(response -> log.debug("发送流式响应：{}", response))
                    .onErrorResume(e -> {
                        log.error("流式API调用失败: {}", e.getMessage());
                        ChatResponseEntity errorResponse = new ChatResponseEntity();
                        errorResponse.setContent("处理请求时发生错误: " + e.getMessage());
                        return Flux.just(errorResponse);
                    });
        } catch (Exception e) {
            log.error("初始化流式请求失败: {}", e.getMessage(), e);
            return Flux.error(new RuntimeException("初始化AI服务失败: " + e.getMessage()));
        }
    }
}
